<?php

namespace Home\Controller;

use Think\Controller;
use Home\Util\CryptAes;

class SupportController extends Controller {

    protected function _initialize() {
        header('Cache-Control: no-cache');
    }

    /**
     * 登录
     */
    public function index() {
        $id = I('get.id');
        $user_agent = I('server.HTTP_USER_AGENT');
        $user_id = session('wap_user_id');
        $para1 = I('get.para1');
        if (!empty($para1)) {
            session('para1', $para1);
        }
        if (strpos($user_agent, 'MicroMessenger') !== false && !is_numeric($user_id)) {
            //微信访问
            header('Location: '
                    . "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . C('APP_ID')
                    . "&redirect_uri=" . urlencode(DREAM_URL . '/index.php?s=/Support/support.html')
                    . "&response_type=code&scope=snsapi_base&state={$id}#wechat_redirect");
        } else {
            //浏览器访问
            //登录用户取ID
            if (!is_numeric($user_id)) {
                //客户端get传值取ID
                import('@.Util.CryptAes');
                $aes = new CryptAes();
                $user_id = json_decode(urldecode($aes->decode(str_replace("-","/",str_replace(" ","+",I('get.para1'))))), true);
            }
            if (is_numeric($user_id)) {
                session('dream_support_user_id', $user_id);
                //本地无记录ID根据接口取数据存储本地
                $support_model = D('Support');
                $support_model->checkUser($user_id);
                header('Location: ' . DREAM_URL . '/index.php?s=/Support/support/state/' . $id . '.html');
            } else {
                header('Location: ' . DREAM_URL . '/Index/login');
            }
        }
    }

    /**
     * 支持页
     * 
     * @param int $id 梦想ID（GET）
     */
    public function support() {
        $id = I('get.state');
		//客户端分享的跳转
        $para1 = I('get.para1');
        if (!empty($para1)) {
            header('Location: ' . DREAM_URL . '/index.php?s=/Support/index/id/' . $id . '.html&para1=' . $para1);
            die;
        }
        $support_model = D('Support');
        $user_id = session('dream_support_user_id');
        if (is_numeric($user_id)) {
            //浏览器访问
            //取支持数
            $this->assign('is_support', $support_model->isSupportByUser($id, $user_id));
        } else {
            //微信访问
            //获取微信用户openid
            $code = I('get.code');
            if(empty($code)) {
                header('Location: ' . DREAM_URL . '/index.php?s=/Support/index/id/' . $id . '.html');
            }
            $openid = $support_model->getWeixinUserOpenid($code);
            //获取是否支持过该内容
            $this->assign('is_support', $support_model->isSupportByWeixin($id, $openid));
        }
        //取梦想及用户数据
        if (!$support_model->createUser($id)) {
            $this->error($support_model->getError());
        }
        $this->assign('dream', $support_model->dream);
        $this->assign('user', $support_model->user);
        //自己的梦想点击我也说一个跳到修改页面
        if ($user_id == $support_model->dream['user_id']) {
            $this->assign('modify_id', $support_model->dream['dream_id']);
        }
        //更新初次显示黑屏状态
        if ($support_model->dream['fist_show'] == 1) {
            $user_model = M('user');
            $support_model->dream['fist_show'] = 0;
            $user_model->save($support_model->dream);
        }
        //取支持数
        $count = $support_model->getSupportCount($id);
        $this->assign('count', $count);
        //访问统计
        $index_controller = A('Index');
        $index_controller->insertIp();
        $this->display();
    }

    /**
     * 执行支持
     */
    public function doSupport() {
        $id = I('get.state');
        $user_id = session('dream_support_user_id');
        //支持人ID
        $support_user_id = 0;
        if (is_numeric($user_id)) {
        	$from_type=0;//在客户端支持
            //浏览器访问
            $dream_support_user_model = M('support_user');
            $map = array(
                'user_id' => $user_id,
                'status' => 0,
            );
            $support_user = $dream_support_user_model->where($map)->find();
            if (!empty($support_user)) {
                //不能自己支持自己
                $dream_model = M('user');
                $dream = $dream_model->find($id);
                if ($dream['user_id'] == $support_user['user_id']) {
                    $this->error('不能支持自己的梦想');
                }
                $support_user_id = $support_user['suport_user_id'];
            } else {
                $this->error('用户不存在');
            }
        } else {
        	$from_type=1;//在微信支持
            //微信访问
            //获取微信用户openid
            $code = I('get.code');
            if(empty($code)) {
                header('Location: ' . DREAM_URL . '/index.php?s=/Support/index/id/' . $id . '.html');
            }
            $support_model = D('Support');
            $info = session('weixin_info');
            if (empty($info)) {
                $info = $support_model->getWeixinUserInfo($code);
                session('weixin_info', $info);
            }
            //检查openid是否已存在
            $dream_support_user_model = M('support_user');
            $map['open_id'] = $info['openid'];
            $map['status'] = 0;
            $support_user = $dream_support_user_model->where($map)->find();
            if (!empty($support_user)) {
                $support_user_id = $support_user['suport_user_id'];
            } else {
                $data = array(
                    'suport_user_type' => 0,
                    'open_id' => $info['openid'],
                    'suport_user_name' => $info['nickname'],
                    'suport_user_icon' => $info['headimgurl'],
                    'unionid' => $info['unionid'],
                    'other_content' => serialize($info),
                    'create_date' => time(),
                    'update_date' => time(),
                    'status' => 0,
                );
                $insert_id = $dream_support_user_model->add($data);
                if (!$insert_id) {
                    $this->error('提交错误');
                }
                $support_user_id = $insert_id;
            }
        }
        //关系表处理
        $dream_support_model = M('support');
        $map = array(
            'suport_user_id' => $support_user_id,
            'dream_id' => $id,
        );
        if ($dream_support_model->where($map)->find()) {
            $this->error('您已经支持过了');
        }
        $data = array(
            'dream_id' => $id,
            'suport_user_id' => $support_user_id,
        	'from_type' => $from_type,
            'is_suport' => 1,
            'create_date' => time(),
            'update_date' => time(),
            'status' => 0,
        );
        if (!$dream_support_model->add($data)) {
            $this->error('提交错误');
        } else {
            $user_id = session('dream_support_user_id');
            if (is_numeric($user_id)) {
                header('Location: ' . DREAM_URL . '/index.php?s=/Support/support/state/' . $id . '.html');
            } else {
                header('Location: '
                        . "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . C('APP_ID')
                        . "&redirect_uri=" . urlencode(DREAM_URL . '/index.php?s=/Support/support.html')
                        . "&response_type=code&scope=snsapi_base&state={$id}#wechat_redirect");
            }
        }
    }

}
